package com.zhangwei.xutils.utils;

import org.json.JSONObject;

import java.lang.reflect.Field;

/**
 * @author zhangwei
 * @version V1.0
 * @Title: Advanced
 * @Package com.zhangwei.xutils.utils
 * @Description:
 * @date 15/10/19 上午11:09
 */

public class JsonUtils {

    public static Object parseObject(String json, Class cls) {
        Object o = null;
        try {
            o = cls.newInstance();
            JSONObject jsonObject = new JSONObject(json);
            Field[] declaredFields = cls.getDeclaredFields();
            if (declaredFields != null && declaredFields.length > 0) {
                for (Field flied : declaredFields) {
                    String type = flied.getType().toString().substring(flied.getType().toString().lastIndexOf("." + 1));
                    String value = null;
                    if (type.equals("String")) {
                        value = jsonObject.getString(flied.getName());

                    } else if (type.equals("int")) {
                        value = jsonObject.getString(flied.getName());
                    }
                    flied.setAccessible(true);
                    flied.set(o, value);
                }


            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return o;
    }


}
